import base64
import cv2
import numpy as np
from PIL import Image


class ImageProcessor:
    def __init__(self):
        pass

    @staticmethod
    def process_image(image_data):
        image_np = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        success, compressed_image = cv2.imencode(".jpg", gray_image)
        return compressed_image.tobytes()

    @staticmethod
    def image_to_byte_array(image_path):
        with open(image_path, 'rb') as image_file:
            ImageProcessor.compress_image(image_path, image_path)
            encoded_string = base64.b64encode(image_file.read())
            file_content = image_file.read()
        # return FileResponse(image_path, media_type='image/jpeg')
        return encoded_string
        # return Response(content=file_content, media_type='image/jpeg')

    @staticmethod
    def compress_image(image_path, output_path, quality=20):
        # 打开原图片
        img = Image.open(image_path)
        # 使用指定的质量值保存图片
        img.save(output_path, "JPEG", quality=quality)
